// 获取 DOM 元素
const chatHistory = document.getElementById('chat-history');
const userInput = document.getElementById('user-input');
const sendBtn = document.getElementById('send-btn');
const clearBtn = document.getElementById('clear-btn');
const newChatBtn = document.querySelector('.new-chat');
const chatHistoryBtn = document.querySelector('.chart-history');
const rightMenu = document.querySelector('.right'); // 修正选择器，假设右侧菜单的类名是 right

// 缓存聊天记录和历史记录
let chatRecords = [];
const chatHistoryCache = [];
let maxHistoryNum = 10; // 最大历史记录数量
let currentHistoryIndex = 0; // 当前对话索引，0 表示新对话

// 发送消息
sendBtn.addEventListener('click', () => {
    const message = userInput.value.trim();
    if (message) {
        handleUserMessage(message);
        userInput.value = ''; // 清空输入框
    }
});

// 回车发送消息
document.addEventListener('DOMContentLoaded', () => {
    userInput.addEventListener('keydown', (e) => {
        if (e.key === "Enter") {
            sendBtn.click();
        }
    });
});

// 处理用户消息
function handleUserMessage(userMessage) {
    // 添加用户消息到聊天窗口
    appendMessage(userMessage, 'user');

    // 获取 AI 回复
    getAIResponse(userMessage);
}

// 调用后端 API 获取 AI 回复
function getAIResponse(userMessage) {
    fetch('/api/ai-chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: userMessage })
    })
    .then(response => response.json())
    .then(data => {
        const aiMessage = data.choices[0]?.message?.content || "未能获取有效回复";
        appendMessage(aiMessage, 'ai');
    })
    .catch(error => {
        console.error('AI 回复失败:', error);
        appendMessage("AI 发生错误，请稍后再试。", 'ai');
    });
}

// 清除聊天记录
clearBtn.addEventListener('click', () => {
    chatHistory.innerHTML = '';  // 清空聊天记录显示区域
    appendMessage('已清除上下文', 'system');  // 系统消息
    chatRecords = [];  // 清空聊天记录数组
});

// 新建对话记录
newChatBtn.addEventListener('click', () => {
    if (chatHistoryCache.length >= maxHistoryNum) {
        alert('对话记录已达上限！');
        return;
    }

    // 保存当前对话记录到历史记录
    if (chatRecords.length > 0) {
        chatHistoryCache.push([...chatRecords]);
    }

    // 重置当前对话
    chatRecords = [];
    chatHistory.innerHTML = '';
    appendMessage('新对话已开始', 'system');  // 系统消息

    // 更新右侧菜单
    updateRightMenu();
});

// 加载历史对话
function loadHistory(index) {
    chatHistory.innerHTML = '';
    const history = chatHistoryCache[index] || [];
    history.forEach(record => {
        appendMessage(record.message, record.sender);
    });
    currentHistoryIndex = index; // 更新当前对话索引
}

// 删除历史对话
function deleteHistory(index, historyElement) {
    chatHistoryCache.splice(index, 1);
    rightMenu.removeChild(historyElement);
}

// 填充用户输入框
function fillInput(text) {
    userInput.value = text;
}

// 更新右侧菜单
function updateRightMenu() {
    // 清空右侧菜单
    rightMenu.innerHTML = '';

    // 为每个历史记录添加一个项
    chatHistoryCache.forEach((history, index) => {
        const newDiv = document.createElement('div');
        newDiv.classList.add('history-item');

        const historyText = document.createElement('span');
        historyText.textContent = `对话记录 ${index + 1}`;
        newDiv.appendChild(historyText);

        historyText.addEventListener('click', () => {
            loadHistory(index); // 加载选中的历史对话
        });

        const deleteButton = document.createElement('button');
        deleteButton.textContent = '删除';
        deleteButton.addEventListener('click', () => {
            deleteHistory(index, newDiv); // 删除选中的历史对话
        });

        newDiv.appendChild(deleteButton);
        rightMenu.appendChild(newDiv);
    });
}

// 追加消息到聊天窗口
function appendMessage(message, sender) {
    const messageElement = document.createElement('div');
    messageElement.classList.add('chat-message', sender);

    const messageText = document.createElement('p');
    messageText.textContent = message;
    messageElement.appendChild(messageText);

    const messageTime = document.createElement('span');
    messageTime.classList.add('chat-time');
    messageTime.textContent = new Date().toLocaleString();
    messageElement.appendChild(messageTime);

    chatHistory.appendChild(messageElement);

    // 滚动到最新消息
    chatHistory.scrollTop = chatHistory.scrollHeight;
}
